package com.lifeng.patterns.templatemethod;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by lifeng on 2019/10/16.
 * 远程调用抽象类
 */
public abstract class AbstractRemoteCall {
    private static final Logger log = LoggerFactory.getLogger(AbstractRemoteCall.class);

    public Map<String,Object> execute(Map<String,Object> reqMap) throws Exception{
        Object vo = getBean(reqMap);
        Map<String, Object> rspMap = new HashMap<String, Object>();
        Object ret = null;
        try {
            log.debug("请求数据为："+vo);
            ret = executeBiz(vo);
            log.debug("返回数据为："+ret);
        } catch (Exception e) {
            exceptionHandle(e, rspMap);
        }
        rspMap=getRspMap(ret,rspMap);
        return rspMap;
    }

    /** 组装请求参数bean*/
    protected abstract Object getBean(Map<String, Object> reqMap);

    /** 执行业务*/
    public abstract Object executeBiz(Object obj) throws Exception;

    /** 解析转换响应参数*/
    public abstract Map<String, Object> getRspMap(Object ret,Map<String, Object> rspMap) throws Exception;

    /** 异常处理*/
    protected void exceptionHandle(Exception e,Map<String, Object> rspMap) throws Exception{
        if(e instanceof NullPointerException){
            log.error("参数异常",e);
            rspMap.put("code","423");
            rspMap.put("msg","参数异常");
        }else if(e instanceof Exception){
            log.error("系统异常",e);
            rspMap.put("code","500");
            rspMap.put("msg","异常异常");
        }
    }
}
